let width = 300;
let height = 600;
let enableAdd = true; // 是否可以添加水果
let score = 0; // 得分
let gameOver = false;
let type;
var temp = 0;

const config = {
  type: Phaser.AUTO,
  parent: "game",
  width: width,
  height: height,
  backgroundColor: "#ffe8a3",
  scale: {
    mode: Phaser.Scale.FIT,
    autoCenter: Phaser.Scale.CENTER_BOTH,
  },
  scene: {
    preload,
    create,
    update,
  },
  physics: {
    default: "matter",
    matter: {
      gravity: 2,
    },
  },
};

const game = new Phaser.Game(config);

function preload() {
  for (let i = 1; i <= 11; i++) {
    this.load.image(`${i}`, `assets/images/${i}.png`); // 加载水果图片
  }
  this.load.image("endline", "assets/images/endline.png"); // 加载分割线
  this.load.image("background", "assets/images/background.png"); // 加载地面
}

function create() {
  this.matter.world.setBounds();

  const groundSprite = this.add.tileSprite(
    width / 2,
    height - 40 / 2,
    width,
    40,
    "background"
  );
  this.matter.add.gameObject(groundSprite, { isStatic: true });

  const x = width / 2;
  const y = height / 15;

  let fruit = createFruit(this.matter, this.tweens, x, y);

  const endLineSprite = this.add.tileSprite(width / 2, 80, width, 8, "endline");

  endLineSprite.setVisible(true);

  this.matter.add.gameObject(endLineSprite, {
    isStatic: true,
    isSensor: true, // 传感器模式
    label: "endline",
  });

  this.scoreText = this.add
    .text(20, 20, `${score}`, { font: "20px Arial Black", color: "#ffe325" })
    .setStroke("#974c1e", 12);

  this.input.on("pointerdown", (point) => {
    if (enableAdd) {
      enableAdd = false;
      //先x轴上移动到手指按下的点
      this.tweens.add({
        targets: fruit,
        x: point.x,
        duration: 100,
        ease: "Power1",
        onComplete: () => {
          //取消静止状态，让物体掉落
          fruit.setStatic(false);
          //1s后生成新的水果
          setTimeout(() => {
            fruit = createFruit(this.matter, this.tweens, x, y);
            enableAdd = true;
          }, 1000);
        },
      });
    }
  });

  this.matter.world.on("collisionstart", (event) => {
    // 水果碰撞判断是否合成
    temp = 0;

    let arr = event.source.pairs.list;

    let len = arr.length;

    for (let i = 0; i < len; i++) {
      let fA = arr[i].bodyA;
      let fB = arr[i].bodyB;

      if (fB.label == "endline" || fA.label == "endline") {
        temp += 1;
      }

      if (temp > 2) {
        gameOver = true;
        console.log("game over");
      }

      const sameFruit = fA.label === fB.label; //判断是否为同一个水果
      const notWatermelon = fA.label !== "11"; // 判断是否为大西瓜
      const live = !fA.isStatic && !fB.isStatic;

      if (sameFruit && notWatermelon && live) {
        fA.isStatic = true;
        fB.isStatic = true;

        const { x, y } = fA.position;

        const label = Number.parseInt(fA.label) + 1;

        this.tweens.add({
          targets: fB.position,
          props: {
            x: { value: x, ease: "Power3" },
            y: { value: y, ease: "Power3" },
          },
          duration: 150,
          onComplete: () => {
            //销毁西瓜
            fA.gameObject.alpha = 0;
            fB.gameObject.alpha = 0;
            fA.destroy();
            fB.destroy();

            //生成新的西瓜
            createFruit(this.matter, this.tweens, x, y, `${label}`, false);
            enableAdd = true;
          },
        });

        let currentScore = label - 1;

        if (currentScore == 10) {
          score += 100;
        } else {
          score += currentScore;
        }

        this.scoreText.setText(score);
      }
    }
  });

}

function update() {
  if (gameOver) {
    // 游戏结束
    this.infoText = this.add
      .text(width / 5 , height / 2 - 80, `恭喜您获得${score}分`, {
        font: "30px Arial Black",
        color: "#ffe325",
        align: "center",
      })
      .setStroke("#974c1e", 12);
    
    this.tweens.destroy();
  }
}

function createFruit(matter, tweens, x, y, key, isStatic = true) {
  // 创建水果
  if (!key) {
    let num = Math.floor(Math.random() * 5) + 1;
    key = `${num}`;
    type = key;
  }

  const fruit = matter.add.image(x, y, key);

  fruit.setBody(
    {
      type: "circle",
      radius: fruit.width / 2,
    },
    {
      isStatic,
      label: key,
    }
  );

  tweens.add({
    targets: fruit,
    scale: {
      from: 0,
      to: 1,
    },
    ease: "Back",
    easeParams: [3.5],
    duration: 200,
  });

  return fruit;
}
